package cn.stylefeng.guns.sys.modular.system.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.auth.model.LoginUser;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.modular.system.db4.model.result.ShopOwnerInfoResult;
import cn.stylefeng.guns.sys.modular.system.db4.service.BizShopService;
import cn.stylefeng.guns.sys.modular.system.db4.service.MenDianInfoService;
import cn.stylefeng.guns.sys.modular.system.db5.model.result.MenDianInfoResult;
import cn.stylefeng.guns.sys.modular.system.entity.BtyGoodsPay;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyGoodsPayParam;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyGoodsPayResult;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyGoodsPayShopOwerResult;
import cn.stylefeng.guns.sys.modular.system.service.BtyGoodsPayService;
import cn.stylefeng.guns.sys.modular.system.service.PushMsgService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.reqres.response.SuccessResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;


/**
 * 控制器
 *
 * @author jiangge
 * @Date 2021-07-08 11:46:51
 */
@Controller
@RequestMapping("/btyGoodsPay")
public class BtyGoodsPayController extends BaseController {

    private String PREFIX = "/modular/system/btyGoodsPay";

    @Autowired
    private BtyGoodsPayService btyGoodsPayService;

    @Autowired
    private PushMsgService pushMsgService;

    @Autowired
    private BizShopService bizShopService;
    @Autowired
    private MenDianInfoService menDianInfoService;

    /**
     * 跳转到主页面
     *
     * @author jiangge
     * @Date 2021-07-08
     */
    @RequestMapping("")
    public String index(Model model) {
        String dateStr = DateUtil.getLastMonthStr();
        model.addAttribute("dateStr", dateStr);
        return PREFIX + "/btyGoodsPay.html";
    }

    @RequestMapping("/allData")
    public String indexAllData(Model model) {
        String dateStr = DateUtil.getLastMonthStr();
        model.addAttribute("dateStr", dateStr);
        return PREFIX + "/btyGoodsPayAllData.html";
    }

    /**
     * 新增页面
     *
     * @author jiangge
     * @Date 2021-07-08
     */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "/btyGoodsPay_add.html";
    }

    /**
     * 编辑页面
     *
     * @author jiangge
     * @Date 2021-07-08
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/btyGoodsPay_edit.html";
    }

    @RequestMapping("/selectDz")
    public String selectDz(BtyGoodsPayParam btyGoodsPayParam, Model model) {
        model.addAttribute("id", btyGoodsPayParam.getId());
        model.addAttribute("bh", btyGoodsPayParam.getDzBh());
        model.addAttribute("bh1", btyGoodsPayParam.getBh1());
        model.addAttribute("bh2", btyGoodsPayParam.getBh2());
        model.addAttribute("bh3", btyGoodsPayParam.getBh3());
        model.addAttribute("bh4", btyGoodsPayParam.getBh4());
        model.addAttribute("bh5", btyGoodsPayParam.getBh5());
        return PREFIX + "/btyGoodsPay_selectDz.html";
    }

    /**
     * 新增接口
     *
     * @author jiangge
     * @Date 2021-07-08
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(BtyGoodsPayParam btyGoodsPayParam) {
        this.btyGoodsPayService.add(btyGoodsPayParam);
        return ResponseData.success();
    }

    /**
     * 新增接口
     *
     * @author gyz
     * @Date 2020-11-02
     */
    @RequestMapping("/initData")
    @ResponseBody
    public ResponseData initData(BtyGoodsPayParam param) {

        //当前登录者姓名就是会计的名字
        LoginUser currentUser = LoginContextHolder.getContext().getUser();
        String userName = currentUser.getName();

        ResponseData responseData = this.btyGoodsPayService.initData(userName, param);
        return responseData;
    }

    /**
     * 同步店名
     *
     */
    @RequestMapping("/synData")
    @ResponseBody
    public ResponseData synData(BtyGoodsPayParam param) {

        //当前登录者姓名就是会计的名字
        LoginUser currentUser = LoginContextHolder.getContext().getUser();
        String userName = currentUser.getName();
        //店长信息
        Map<String, ShopOwnerInfoResult> map = bizShopService.shopOwnerInfoList();

        ResponseData responseData = this.btyGoodsPayService.synData(userName, param, map);
        return responseData;
    }

    /**
     * 编辑接口
     *
     * @author jiangge
     * @Date 2021-07-08
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(BtyGoodsPayParam btyGoodsPayParam) {
        List<String> list = new ArrayList<>();
        if (ToolUtil.isNotEmpty(btyGoodsPayParam.getDzBh())){
            list.add(btyGoodsPayParam.getDzBh());
        }
        if (ToolUtil.isNotEmpty(btyGoodsPayParam.getBh1())){
            list.add(btyGoodsPayParam.getBh1());
        }
        if (ToolUtil.isNotEmpty(btyGoodsPayParam.getBh2())){
            list.add(btyGoodsPayParam.getBh2());
        }
        if (ToolUtil.isNotEmpty(btyGoodsPayParam.getBh3())){
            list.add(btyGoodsPayParam.getBh3());
        }
        if (ToolUtil.isNotEmpty(btyGoodsPayParam.getBh4())){
            list.add(btyGoodsPayParam.getBh4());
        }
        if (ToolUtil.isNotEmpty(btyGoodsPayParam.getBh5())){
            list.add(btyGoodsPayParam.getBh5());
        }
        Set<String> set = new HashSet<>(list);
        boolean result = list.size() == set.size() ? true : false;
        if (!result){
            return ResponseData.error("不可选择重复人员!");
        }

        ResponseData responseData = this.btyGoodsPayService.update(btyGoodsPayParam);
        return responseData;
    }

    /**
     * 删除接口
     *
     * @author jiangge
     * @Date 2021-07-08
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(BtyGoodsPayParam btyGoodsPayParam) {
        this.btyGoodsPayService.delete(btyGoodsPayParam);
        return ResponseData.success();
    }

    /**
     * 发送店长，修改状态 从0到1,除了通过的都可以再次发送
     *
     * @author jiangge
     * @Date 2021-07-08
     */
    @RequestMapping("/send")
    @ResponseBody
    public ResponseData send(BtyGoodsPayParam btyGoodsPayParam) {
        //TODO-1 修改状态为已发送
        BtyGoodsPay btyGoodsPay = this.btyGoodsPayService.getById(btyGoodsPayParam.getId());
        //已经通过的不能再次发送
        if (btyGoodsPay.getStatus() == 3) {
            return ResponseData.error(1, "已经通过货赔审核，不可再次发送");
        }

        if (btyGoodsPay.getSumMoney() == null || btyGoodsPay.getSumMoney().compareTo(BigDecimal.ZERO) == 0) {
            return ResponseData.error(1, "货赔总金额为0,不需要发送店长");
        }
        //改状态为 1：已发送
        btyGoodsPay.setStatus(1);
        this.btyGoodsPayService.updateById(btyGoodsPay);
        List<MenDianInfoResult> allMenDianInfoList = this.menDianInfoService.findAllMenDianInfo();
        Map<String, String> yaoMaDzMobileMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(allMenDianInfoList)) {
            for (MenDianInfoResult result : allMenDianInfoList) {
                yaoMaDzMobileMap.put(result.getBh(), result.getLxfs());
            }
        }
        String dzMobile = yaoMaDzMobileMap.get(btyGoodsPay.getYaoma());
        //TODO-2 发送信息-下一行出错只会发送信息不成功，但不影响返回
        pushMsgService.pushMsg(btyGoodsPay, dzMobile);
        pushMsgService.pushMsgToApp(btyGoodsPay, dzMobile);
        pushMsgService.pushMsgToIM(btyGoodsPay, dzMobile);

        return ResponseData.success();
    }

    /**
     * 发送店长，修改状态 从0到1,除了通过的都可以再次发送
     *
     * @author jiangge
     * @Date 2021-07-08
     */
    @RequestMapping("/batchSend")
    @ResponseBody
    public ResponseData batchSend(BtyGoodsPayParam btyGoodsPayParam) {
        //发送成功的门店
        String failedSendName = "";
        int successNum = 0;
        int notSuccessNum = 0;
        String zeroDataName = "";
        int zeroDataNum = 0;

        //TODO-1 修改状态为已发送
        String[] strArray = btyGoodsPayParam.getIds().split(",");
        List<String> ids = Arrays.asList(strArray);

        for (String id : ids) {
            BtyGoodsPay btyGoodsPay = this.btyGoodsPayService.getById(id);
            //货赔总金额为0，不发送
            if (btyGoodsPay.getSumMoney() == null || btyGoodsPay.getSumMoney().compareTo(BigDecimal.ZERO) == 0) {
                if (StringUtils.isBlank(zeroDataName)) {
                    zeroDataName = btyGoodsPay.getDm();
                } else {
                    zeroDataName = zeroDataName + "," + btyGoodsPay.getDm();
                }
                zeroDataNum = zeroDataNum + 1;
                continue;
            }

            //已经通过的不能再次发送
            if (btyGoodsPay.getStatus() == 3) {
                if (StringUtils.isBlank(failedSendName)) {
                    failedSendName = btyGoodsPay.getDm();
                } else {
                    failedSendName = failedSendName + "," + btyGoodsPay.getDm();
                }
                notSuccessNum = notSuccessNum + 1;
                continue;
            }
            //改状态为 1：已发送
            btyGoodsPay.setStatus(1);
            this.btyGoodsPayService.updateById(btyGoodsPay);
            successNum = successNum + 1;

            List<MenDianInfoResult> allMenDianInfoList = this.btyGoodsPayService.findAllMenDianInfo();
            Map<String, String> yaoMaDzMobileMap = new HashMap<>();
            if (CollectionUtil.isNotEmpty(allMenDianInfoList)) {
                for (MenDianInfoResult result : allMenDianInfoList) {
                    yaoMaDzMobileMap.put(result.getBh(), result.getLxfs());
                }
            }

            String dzMobile = yaoMaDzMobileMap.get(btyGoodsPay.getYaoma());
            //TODO-2 推送公众号消息
            pushMsgService.pushMsg(btyGoodsPay, dzMobile);
            //TODO-3 推送小妖app信息或小妖IM消息
            pushMsgService.pushMsgToApp(btyGoodsPay, dzMobile);
            pushMsgService.pushMsgToIM(btyGoodsPay, dzMobile);
        }

        if (notSuccessNum > 0) {
            if (!(zeroDataNum > 0)) {
                return new SuccessResponseData(201, "发送成功数：" + successNum + "条,</br>发送失败数：" + notSuccessNum + "条,</br>发送失败门店：" + failedSendName + ",</br>失败原因：已经审核通过的数据不会再次发送", null);
            }
            if (zeroDataNum > 0) {
                return new SuccessResponseData(201, "发送成功数：" + successNum + "条,</br>发送失败数：" + notSuccessNum + "条,</br>已经审核通过,再次发送失败门店：" + failedSendName + ",</br>货赔总金额为0，发送失败门店：" + zeroDataName, null);
            }
        }

        if (zeroDataNum > 0) {
            if (!(zeroDataNum > 0)) {
                return new SuccessResponseData(201, "发送成功数：" + successNum + ",</br>失败原因：已经审核通过的数据不会再次发送", null);
            }
            if (zeroDataNum > 0) {
                return new SuccessResponseData(201, "发送成功数：" + successNum + ",</br>货赔总金额为0，发送失败门店：" + zeroDataName, null);
            }
        }

        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author jiangge
     * @Date 2021-07-08
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(BtyGoodsPayParam btyGoodsPayParam) {
        BtyGoodsPay detail = this.btyGoodsPayService.getById(btyGoodsPayParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author jiangge
     * @Date 2021-07-08
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(BtyGoodsPayParam btyGoodsPayParam) {

        //当前登录人
        LoginUser currentUser = LoginContextHolder.getContext().getUser();
        String userName = currentUser.getName();
        btyGoodsPayParam.setLoginUserName(userName);
        btyGoodsPayParam.setSeeAllData("self");
        //店长信息
        Map<String, ShopOwnerInfoResult> map = bizShopService.shopOwnerInfoList();
        LayuiPageInfo pageInfo = this.btyGoodsPayService.findPageBySpec(btyGoodsPayParam, map);
        return pageInfo;
    }

    /**
     * 查询列表
     *
     * @author jiangge
     * @Date 2021-07-08
     */
    @ResponseBody
    @RequestMapping("/listAll")
    public LayuiPageInfo listAll(BtyGoodsPayParam btyGoodsPayParam) {

        //当前登录人
        LoginUser currentUser = LoginContextHolder.getContext().getUser();
        String userName = currentUser.getName();
        btyGoodsPayParam.setLoginUserName(userName);
        btyGoodsPayParam.setSeeAllData("all");
        //店长信息
        Map<String, ShopOwnerInfoResult> map = bizShopService.shopOwnerInfoList();
        LayuiPageInfo pageInfo = this.btyGoodsPayService.findPageBySpec(btyGoodsPayParam, map);
        return pageInfo;
    }

    /**
     * 审核:改变状态 3：已通过，4：已驳回
     */
    @RequestMapping(value = "/audit", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData adminAudit(BtyGoodsPayParam param) {
        ResponseData responseData = this.btyGoodsPayService.audit(param);
        return responseData;
    }

    /**
     * 批量审核:改变状态 3：已通过，4：已驳回
     *
     */
    @RequestMapping("/auditBatch")
    @ResponseBody
    public ResponseData auditBatch(BtyGoodsPayParam btyGoodsPayParam) {
        return btyGoodsPayService.auditBatch(btyGoodsPayParam);
    }


    /**
     * 审核:改变状态 0：撤回
     */
    @RequestMapping(value = "/revoke", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData revoke(BtyGoodsPayParam param) {
        ResponseData responseData = this.btyGoodsPayService.revoke(param);
        return responseData;
    }

    /**
     * 查询所有财务人员
     *
     * @author jiangge
     * @Date 2020-09-04
     */
    @ResponseBody
    @RequestMapping("/selectAllCwry")
    public List<BtyGoodsPayResult> selectAllCwry(BtyGoodsPayParam param) {
        List<BtyGoodsPayResult> resultList = this.btyGoodsPayService.selectAllCwry(param);
        return resultList;
    }

    /**
     * 查询店长
     * @param param
     * @return
     */
    @ResponseBody
    @RequestMapping("/selectShopOwer")
    public List<BtyGoodsPayShopOwerResult> selectShopOwer(BtyGoodsPayParam param) {
        List<BtyGoodsPayShopOwerResult> resultList = this.btyGoodsPayService.selectShopOwer(param);
        return resultList;
    }

    //导出
    @RequestMapping("/listExport")
    public ResponseEntity<byte[]> exportExcel(HttpServletRequest request, HttpServletResponse response, BtyGoodsPayParam param) {
        //当前登录人
        LoginUser currentUser = LoginContextHolder.getContext().getUser();
        String userName = currentUser.getName();
        param.setLoginUserName(userName);
        param.setSeeAllData("self");
        //店长信息
        Map<String, ShopOwnerInfoResult> map = bizShopService.shopOwnerInfoList();
        return this.btyGoodsPayService.exportExcel(request, response, param, map);
    }

    //导出
    @RequestMapping("/listAllExport")
    public ResponseEntity<byte[]> exportAllExcel(HttpServletRequest request, HttpServletResponse response, BtyGoodsPayParam param) {
        //当前登录人
        LoginUser currentUser = LoginContextHolder.getContext().getUser();
        String userName = currentUser.getName();
        param.setLoginUserName(userName);
        param.setSeeAllData("all");
        //店长信息
        Map<String, ShopOwnerInfoResult> map = bizShopService.shopOwnerInfoList();
        return this.btyGoodsPayService.exportExcel(request, response, param, map);
    }

    /**
     * 同步货赔总金额
     * @return
     */
    @ResponseBody
    @RequestMapping("/editSumMoney")
    public ResponseData editSumMoney(String date){
        return btyGoodsPayService.editSumMoney(date);
    }



}


